package com.airbnb.mvrx.sample.features.clickread.models

import android.support.v4.app.FragmentActivity
import com.airbnb.mvrx.*
import com.airbnb.mvrx.sample.Utils
import com.airbnb.mvrx.sample.core.MvRxViewModel
import com.airbnb.mvrx.sample.models.YTResponse
import com.airbnb.mvrx.sample.network.BooklnService
import org.json.JSONObject
import org.koin.android.ext.android.inject
import java.util.*

data class ClickReadState(val resp: Async<YTResponse> = Uninitialized) : MvRxState
class ClickReadViewModel(initialState: ClickReadState, private val booklnService: BooklnService) : MvRxViewModel<ClickReadState>(initialState) {
    init {
        fetchClickRead()
    }

    private fun fetchClickRead() = withState {
        val data: String = JSONObject().put("bookId", 26842).toString()
        val map: MutableMap<String, Any> = HashMap()
        map.put("_data", data)
        map.putAll(Utils.getCommonParam())
        booklnService.fetchClickRead(map).execute { copy(resp = it) }
    }

    companion object : MvRxViewModelFactory<ClickReadState> {
        @JvmStatic
        override fun create(activity: FragmentActivity, state: ClickReadState)
                : BaseMvRxViewModel<ClickReadState> {
            val service: BooklnService by activity.inject()
            return ClickReadViewModel(state, service)
        }

    }

    fun imageUrlFromResId(resId: Int?, resIdSign: String): String {
        return Utils.format("/resourceservice/mediaplay.do?resId=%d&resIdSign=%s&mediaType=4",
                resId, resIdSign)
    }


}